package exception

import (
	"github.com/go-playground/validator/v10"
	"reflect"
	"strings"
)

func ThrowsErr(err error) {
	panic(err)
}

func ThrowsValid(err error, r interface{}) {
	if err != nil {
		switch err.(type) {
		case validator.ValidationErrors:
			e := (err).(validator.ValidationErrors)
			errMsg := getError(e, r)
			panic(DError{Code: "REQUEST_PARAMS_ERR", Err: errMsg})
			break
		default:
			ThrowsErr(err)
			break
		}
	}
}

// 自定义错误消息
func getError(errs validator.ValidationErrors, r interface{}) string {
	s := reflect.TypeOf(r)
	for _, fieldError := range errs {
		filed, _ := s.FieldByName(fieldError.Field())
		// 获取统一错误消息
		errText := filed.Tag.Get("msg")
		if errText != "" {
			return errText
		}
		jsonTag := filed.Tag.Get("json")
		fieldName := ""
		if jsonTag == "" {
			fieldName = fieldError.Field()
		} else {
			fieldName = strings.Split(jsonTag, ",")[0]
		}
		return fieldName + " " + fieldError.Tag()
	}
	return ""
}

type DError struct {
	Err  string
	Code string
}

func ThrowsErrS(code, err string) {
	panic(DError{Code: code, Err: err})
}

func AssertThrowableErr(throwable bool, err error) {
	if throwable {
		ThrowsErr(err)
	}
}
func AssertThrowable(throwable bool, code, err string) {
	if throwable {
		ThrowsErrS(code, err)
	}
}
